from sqlalchemy.orm import Session
from app.core.responses import Response
from app.database import engine
from app.models import Points as PointsModel, PointsRecord as RecordModel, Users as UsersModel
from app.schemas.user_points import Points, Record
from app.services.orm import pagination


class UserPointsService:
    @staticmethod
    def index(page: int, pageSize: int):
        data = pagination(page, pageSize, PointsModel)
        return Response.success(data=data)

    @staticmethod
    def create(form: Points):
        with Session(engine) as session:
            points = PointsModel(**form.dict())
            session.add(points)
            session.commit()
        return True

    @staticmethod
    def delete(id: int):
        with Session(engine) as session:
            session.query(PointsModel).filter(PointsModel.id == id).delete()
            session.commit()
        return True

    @staticmethod
    def update(id: int, form: Points):
        with Session(engine) as session:
            music = session.query(PointsModel).filter_by(id=id)
            music.update(form.dict())
            session.commit()
        return True

    @staticmethod
    def create_record(user_id, form: Record):
        with Session(engine) as session:
            try:
                points = session.query(PointsModel).filter_by(id=form.pid).first()
                price = points.price
                points = points.points
                form.uid = user_id
                form.price = price
                form.points = points
                record = RecordModel(**form.dict())
                session.add(record)
                session.commit()
            except Exception as e:
                session.rollback()
                print(e)
                return False

            try:
                data = session.query(UsersModel).filter_by(id=user_id)
                user = data.first()
                data.update({'points': user.points + points})
                session.commit()
            except Exception as e:
                session.rollback()
                print(e)
                return False
        return True

    @staticmethod
    def delete_record(id: int):
        with Session(engine) as session:
            session.query(RecordModel).filter(RecordModel.id == id).delete()
            session.commit()
        return True
